<?php
namespace app\controllers;

use app\models\Goods;
use Codeception\Module\Redis;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\EntryForm;
use app\models\Order;

class SeckController extends Controller
{
    //创建redis 放入redis
    public function actionCreatelist(){
        //实例化
        $goods = new Goods();
        //获取商品表中所有的信息
        $data=$goods->getAll();
//        print_r($data);

        //实例化
        $redis = new \Redis();
        //redis连接
        $redis->pconnect("127.0.0.1",6379);
        //指定展示库号
        $redis->select(13);

        foreach($data as $key=>$value){
            for($i=1;$i<=$value['stock'];$i++){
                $redis->lPush("goods".$value['id'],$i);
            }
        }

    }
    public function actionGoods_show(){
        //实例化
        $goods = new Goods();
        //获取商品表中所有的信息
        $data=$goods->getAll();
        return $this->render("show",['data'=>$data]);
    }
    public function actionMiaosha(){
        $id=Yii::$app->request->post();
//        print_r($id);
        $key="goods".$id;

        //实例化
        $redis = new \Redis();
        //redis连接
        $redis->pconnect("127.0.0.1",6379);
        //指定展示库号
        $redis->select(13);

        //判断 键名
        if($redis->lLen($key)>0){
            //redis-1
            $redis->lPop($key);

            //创建订单表  入库数据
            //实例化订单表
            $order = new \Order();
            //订单号
            $order_name=hwj.rand(99999,999999);
            //创建时间
            $createtime=time();
            $order->order_name=$order_name;
            $order->createtime=$createtime;
            $order->goods_id=$id;
            $order->save();

           echo json_encode(['code'=>0,'msg'=>"抢购成功"]);
        }else{
            echo json_encode(['code'=>1,'msg'=>"抢购失败"]);
        }
    }


    //添加商品
    public function actionAddgoods(){
        //渲染
        return $this->render("addgoods");
    }
    //添加数据
    public function actionAdddo(){
        $data=Yii::$app->request->post();
//        print_r($data);
        //实例化
        $goods = new Goods();
        if(!$goods->validate()){
           echo "验证错误";
        }
        $goods->name=$data['name'];
        $goods->price=$data['price'];
        $goods->stock=$data['stock'];
        $goods->save();
    }
}



?>